﻿/*
Copyright (c) 2011, Pawel Szczurek
All rights reserved.


Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:


Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.

Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without
specific prior written permission.


THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using TUVienna.CS_CUP.Runtime;
using Alice.VM;
using System.Globalization;
using Alice.Script;

namespace Alice.Compiler
{
    public class Compiler
    {
        public enum MsgType
        {
            Log,
            Warning,
            Error
        }

        public delegate void LogCallback(MsgType mt, string msg);
        public event LogCallback OnLog;

        public static string Disassemble(Program p)
        {
            string s = "Const:\n\n";

            for (int i = 0; i < p.ConstantValues.Length; i++)
                s += string.Format("[{0:0000}] -> {1}\n", i, p.ConstantValues[i].ToString());

            s += "\n\nCode:\n\n";

            Int64 lastArg = -1;
            for (int i = 0; i < p.ProgramCode.Length; i++)
            {                
                switch ((OPCodes)p.ProgramCode[i])
                {
                    case OPCodes.LoadArg8:
                        s += string.Format("[{0:0000}] -> {1} {2}\n", i, ((OPCodes)p.ProgramCode[i]).ToString(), lastArg = ((sbyte)p.ProgramCode[i + 1]));
                        i++;
                        break;
                    case OPCodes.LoadArg16:
                        s += string.Format("[{0:0000}] -> {1} {2}\n", i, ((OPCodes)p.ProgramCode[i]).ToString(), lastArg = BitConverter.ToInt16(p.ProgramCode, i + 1));
                        i += 2;
                        break;
                    case OPCodes.LoadArg32:
                        s += string.Format("[{0:0000}] -> {1} {2}\n", i, ((OPCodes)p.ProgramCode[i]).ToString(), lastArg = BitConverter.ToInt32(p.ProgramCode, i + 1));
                        i += 4;
                        break;
                  /*  case OPCodes.LoadArg64:
                        s += string.Format("[{0:0000}] -> {1} {2}\n", i, ((OPCodes)p.ProgramCode[i]).ToString(), lastArg = BitConverter.ToInt64(p.ProgramCode, i + 1));
                        i += 8;
                        break;*/

                    case OPCodes.LoadSpecial:
                        s += string.Format("[{0:0000}] -> {1} \t//[{2}]\n", i, ((OPCodes)p.ProgramCode[i]).ToString(), ((SpecialValues)lastArg).ToString());
                        lastArg = -1;
                        break;
                    case OPCodes.LoadConst:
                        s += string.Format("[{0:0000}] -> {1} \t\t//{2}\n", i, ((OPCodes)p.ProgramCode[i]).ToString(), p.ConstantValues[lastArg].ToString());
                        lastArg = -1;
                        break;
                    case OPCodes.Jump:
                        s += string.Format("[{0:0000}] -> {1} \t\t\t//[{2:0000}]\n", i, ((OPCodes)p.ProgramCode[i]).ToString(), i + lastArg + 1);
                        lastArg = -1;
                        break;
                    case OPCodes.JumpIfNotTrue:
                        s += string.Format("[{0:0000}] -> {1} \t//[{2:0000}]\n", i, ((OPCodes)p.ProgramCode[i]).ToString(), i + lastArg + 1);
                        lastArg = -1;
                        break;
                    default:
                        s += string.Format("[{0:0000}] -> {1}\n", i, ((OPCodes)p.ProgramCode[i]).ToString());
                        lastArg = -1;
                        break;
                }
            }

            return s;
        }

        public Program Compile(string source)
        {
            Code.ScriptCode code = Parse(ref source);
            /*ScriptCode sc = new ScriptCode();

            foreach (var entityKVP in code.Entities)
            {
                foreach (var actionKVP in entityKVP.Value.Actions)
                {
                    sc.SetProgram(entityKVP.Key, actionKVP.Key, actionKVP.Value.Program);
                }
            }

            return sc;*/

            CodeGenerator cg = new CodeGenerator();
            code.GenerateCode(cg);
            Program p = cg.Finish();
            return p;

        }

        Code.ScriptCode Parse(ref string source)
        {
            TextReader tr = new StringReader(source);

            try
            {

                parser p = new parser(new Yylex(tr));
                TUVienna.CS_CUP.Runtime.Symbol s = p.parse();
                return (Code.ScriptCode)s.value;
            }
            catch (ParserException ex)
            {
                string errorInfo = string.Format("parse error\n[SourceBegin]\n{0}\n[SourceEnd]\nMsg:{1}\n", source, ex.Message);

                Symbol s = ex.ParserInfo as Symbol;
                if (s != null)
                {
                    int line;
                    int charInLine;

                    CharNumToLine(source, s.left, out line, out charInLine);

                    errorInfo += string.Format("Extra Info: line:({0}) char:({1}) Token:({2}) char range:({3})-({4})\n",
                        line + 1, charInLine + 1, TokenName(s), s.left, s.right);
                }

                InternalLog(MsgType.Error, errorInfo);
            }

            return null;
        }
        static void CharNumToLine(string source, int charNum, out int line, out int charInLine)
        {
            line = 0;
            charInLine = 0;

            for (int i = 0; i < source.Length && i <= charNum; i++)
            {
                if (source[i] == '\n')
                {
                    line++;
                    charInLine = 0;
                }
                else
                {
                    charInLine++;
                }
            }
        }
        static string TokenName(Symbol sid)
        {
            foreach (System.Reflection.FieldInfo fi in typeof(sym).GetFields())
            {
                if (((int)fi.GetValue(m_symbolTable)) == sid.sym)
                {
                    return fi.Name;
                }
            }

            return string.Format("Token({0})", sid.sym);
        }

        internal void InternalLog(MsgType mt, string msg, params object[] p)
        {
            InternalLog(mt, string.Format(msg, p));
        }
        internal void InternalLog(MsgType mt, string msg)
        {
            if (OnLog != null)
                OnLog(mt, msg + '\n');
        }

        readonly static sym m_symbolTable = new sym();
    }
}
